import { Component } from "react";
import sub from "./sub.js"

export default class Votemain extends Component{
    state={
        supNum:0,
        oppNum:0
    }
    add=(type)=>{//this--->Vote类
        if(type=="sup"){
            this.setState({
                supNum:this.state.supNum+1
            })
        }else if(type=="opp"){
            this.setState({
                oppNum:this.state.oppNum+1
            })
        }
    }
    render(){
        let {supNum,oppNum}=this.state;
        return <div>
            <h2>支持人数：{supNum}</h2>
            <h2>反对人数：{oppNum}</h2>
            <h2>支持率：{this.computed()}</h2>
        </div>
    }
    computed=()=>{
      let {supNum,oppNum}=this.state;
      let total=supNum+oppNum;
      if(total<=0){
         return "0.00%";
      }
      return (supNum/total*100).toFixed(2)+"%";
    }
    componentDidMount(){
       sub.on("add",this.add)
    }
}